package br.com.estevam.gallery.tools;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.*;

public final class DBConnection {
	
	// Referência para instância única da conexão.
	private static Connection instanceSrvsfiec05 = null;
	
	// Variaveis
	protected static String url = getDbProperties().getProperty("url");
	protected static String forName = getDbProperties().getProperty("driver");
	protected static String user = getDbProperties().getProperty("login");
	protected static String passwd = getDbProperties().getProperty("senha");

	private static Properties getDbProperties() {
		Properties props = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(Util.getWebappPath()+"WEB-INF"+Util.getS()+"dbconnection.properties");
			props.load(fis);  
			fis.close();
		}
		catch (IOException ex) {
			ex.printStackTrace();
		}
		
		return props;
	}
	
	// Construtor privado da classe
	private DBConnection() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
		instantiateInstanceSrvsfiec05();
	}

	private static void instantiateInstanceSrvsfiec05() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException{
		Class.forName(forName).newInstance();
		instanceSrvsfiec05 = DriverManager.getConnection(url+"?user="+user+"&password="+passwd);

		// Informando a base utilizada.
		System.out.println("[INFO] DBConnection - " + url.trim() + " - " + forName.trim() );
		System.out.println("[INFO] PATH: "+Util.getWebappPath()+"WEB-INF"+Util.getS()+"dbconnection.properties");
	}

	public synchronized static Connection getConnection() throws 
	ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
		if (instanceSrvsfiec05==null) // SRVSFIEC05 é rei do Produção
		{	// Lazy instantiation, só quando for preciso
			new DBConnection();
		}
		
		return instanceSrvsfiec05;
	}
	
	public synchronized static void shutdown() throws SQLException {
		if (instanceSrvsfiec05!=null) {

			instanceSrvsfiec05.close();
			instanceSrvsfiec05 = null;

		}
	}
}
